package com.example.xmpic.ui.utils;

import com.example.xmpic.ui.data.CameraBean;
import com.example.xmpic.ui.data.CameraBeanDao;

/**
 * @author skygge
 * @date 2020/7/22.
 * GitHub：javofxu@github.com
 * email：skygge@yeah.net
 * description：
 */
public class CameraDaoUtil {

    private volatile static CameraDaoUtil instance = null;
    private CameraBeanDao mCameraDao;

    public static CameraDaoUtil getInstance() {
        if (instance == null){
            synchronized (CameraDaoUtil.class){
                if (instance == null){
                    instance = new CameraDaoUtil();
                }
            }
        }
        return instance;
    }

    private CameraDaoUtil() {
        mCameraDao = FunSdkInitUtil.getInstance().getDaoSession().getCameraBeanDao();
    }

    /**
     * 添加摄像头
     */
    public void insertCamera(CameraBean camera){
        mCameraDao.insertOrReplace(camera);
    }

    /**
     * 修改摄像头昵称
     */
    public void updateCameraName(String userId, String deviceId, String nickname){
        CameraBean cameraBean = findCamera(userId, deviceId);
        cameraBean.setDeviceName(nickname);
        mCameraDao.update(cameraBean);
    }

    /**
     * 修改摄像头房间名称
     */
    public void updateCameraRoom(String userId, String deviceId, String roomId, String roomName){
        CameraBean cameraBean = findCamera(userId, deviceId);
        cameraBean.setRoomId(roomId);
        cameraBean.setRoomName(roomName);
        mCameraDao.update(cameraBean);
    }

    /**
     * 查询摄像头
     */
    public CameraBean findCamera(String userId, String deviceId){
        return mCameraDao.queryBuilder()
                .where(CameraBeanDao.Properties.UserId.eq(userId),
                        CameraBeanDao.Properties.DeviceId.eq(deviceId))
                .build()
                .unique();
    }

    public CameraBean findCameraByCameraId(String deviceId){
        return mCameraDao.queryBuilder()
                .where(CameraBeanDao.Properties.DeviceId.eq(deviceId))
                .build()
                .unique();
    }

    /**
     * 查询摄像头是否存在
     */
    public boolean isCameraExits(String userId, String deviceId){
        CameraBean cameraBean = findCamera(userId, deviceId);
        return cameraBean!=null;
    }

    /**
     * 删除摄像头
     */
    public void deleteCamera(CameraBean camera){
        mCameraDao.delete(camera);
    }

    /**
     * 根据deviceId删除设备
     */
    public void deleteCameraById(String cameraId){
        mCameraDao.queryBuilder()
                .where(CameraBeanDao.Properties.DeviceId.eq(cameraId))
                .buildDelete().executeDeleteWithoutDetachingEntities();
    }

    /**
     * 删除所有摄像头
     */
    public void deleteAllCamera(){
        mCameraDao.deleteAll();
    }
}
